package me.gall.web.common.appengine.struts2.conventer;

import java.util.Map;

import ognl.DefaultTypeConverter;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class KeyConverter extends DefaultTypeConverter {

    @SuppressWarnings("unchecked")
	public Object convertValue(Map map, Object o, Class toType) {
        if (toType == Key.class) {
        	if(o == null)
        		return null;
            String s = ((String[]) o)[0];
            if(s == null)
            	return null;
            if(s.isEmpty())
            	return null;
            return KeyFactory.stringToKey(s);
        } else if (toType == String.class) {
            Key k = (Key) o;
            if(k == null)
            	return null;
            return KeyFactory.keyToString(k);
        }
        return o;
    }
}
